//
//  LoginViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/10/31.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "MainViewController.h"
#import "LoginViewController.h"
#import "UIView+XL.h"
#import "UserModel.h"
#import "NetworkCommand.h"
#import "NSString+MD5.h"

#import <FIRMessaging.h>
#import <SVProgressHUD.h>
#import <AFNetworking.h>

#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@interface LoginViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (weak, nonatomic) IBOutlet UITextField *userNameTextfield;

@property (weak, nonatomic) IBOutlet UITextField *passwordTextfield;

@property (assign , nonatomic) BOOL isLogin;

@property (strong, nonatomic) UserModel *userModel;

@end

@implementation LoginViewController

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    
    
    self.userNameTextfield.delegate = self;
    
    self.passwordTextfield.delegate = self;
    
    //限制输入长度
    [self.userNameTextfield addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self.passwordTextfield addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.isLogin = false;
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    //判断重新登录
    UserModel * userModel = [[UserModel alloc]init];
    
    userModel = nil;
    
    userModel = [[UserModel alloc]init];
    
    userModel.reLogin = YES;
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    if (!self.isLogin) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    
}

#pragma mark 设置UI
-(void)setUpUI{

    //Login按钮渐变色
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:85.0/255 green:154.0/255 blue:240.0/255 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:111.0/255 green:190.0/255 blue:248.0/255 alpha:1].CGColor];
    gradientLayer.locations = @[@0.0];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1.0);
    gradientLayer.frame = CGRectMake(0, 0, self.loginButton.width, self.loginButton.height);
    [self.loginButton.layer addSublayer:gradientLayer];
    
    //Login按钮圆角
    self.loginButton.layer.masksToBounds = YES;
    
    self.loginButton.layer.cornerRadius = 22;
    
    
    //设置username左侧图片
    self.userNameTextfield.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView * userNameImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_user_2"]];
    
    userNameImageView.frame = CGRectMake(0, 0, self.userNameTextfield.height, self.userNameTextfield.height);
    
    UIView * userNameLeftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.userNameTextfield.height + 30, self.userNameTextfield.height)];
    
    [userNameLeftView addSubview:userNameImageView];
    
    self.userNameTextfield.leftView = userNameLeftView;
    
    
    
    
    
    //设置password左侧图片
    self.passwordTextfield.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView * passwordImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_password_2"]];
    
    passwordImageView.frame = CGRectMake(0, 0, self.passwordTextfield.height, self.passwordTextfield.height);
    
    UIView * passwordLeftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.passwordTextfield.height + 30, self.passwordTextfield.height)];
    
    [passwordLeftView addSubview:passwordImageView];
    
    self.passwordTextfield.leftView = passwordLeftView;
    
    
    
    //设置password右侧按钮
    self.passwordTextfield.rightViewMode = UITextFieldViewModeAlways;
    
    UIButton * hiddenButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [hiddenButton setImage:[UIImage imageNamed:@"ic_password_visiable_2"] forState:UIControlStateNormal];
    
    [hiddenButton setImage:[UIImage imageNamed:@"ic_password_invisiable_2"] forState:UIControlStateSelected];
    
    [hiddenButton addTarget:self action:@selector(hiddenPassword:) forControlEvents:UIControlEventTouchUpInside];
    
    hiddenButton.frame = CGRectMake(0, 5, self.passwordTextfield.height, self.passwordTextfield.height - 5);
    
    hiddenButton.selected = YES;
    
    self.passwordTextfield.rightView = hiddenButton;
    
    //记住账号密码
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    if ([userDefaults objectForKey:UD_USERNAME]) {
        
        [self.userNameTextfield setText:[userDefaults objectForKey:UD_USERNAME]];
        
    }
    
    
}

#pragma mark 隐藏密码按钮
-(void)hiddenPassword:(UIButton *)sender{
    
    sender.selected = !sender.selected;
    
    self.passwordTextfield.secureTextEntry = !self.passwordTextfield.secureTextEntry;
    
}

#pragma mark 收起键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.userNameTextfield resignFirstResponder];
    
    [self.passwordTextfield resignFirstResponder];
    
    
}

#pragma mark 点击登录
- (IBAction)touchLoginButton:(id)sender {
    
    if (self.userNameTextfield.text.length == 0 || self.userNameTextfield.text.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"Password or Username can not be empty."];
        
        [SVProgressHUD dismissWithDelay:1];
        
        return;
        
    }
    
    [SVProgressHUD showWithStatus:@"Please wait..."];
    
    
    [self accessToken];
    
//    [self presentViewController:navigationController animated:YES completion:nil];
    
}


#pragma mark 登录请求
-(void)accessToken{
    
    NSMutableDictionary * parameters = [ NSMutableDictionary dictionary];
    parameters[NC_USER_GUID] = [self getUniqueStrByUUID];
    parameters[NC_TERMINAL_MODEL] = @"ffffffff";
    parameters[NC_PLAT_FORM] = @"IOS";
    parameters[NC_ACCOUNT_TYPE] = @1;
    parameters[NC_USER_NAME] = self.userNameTextfield.text;
    
    NSString * newPassword = [NSString stringWithFormat:@"HYZ%@%@",self.userNameTextfield.text,self.passwordTextfield.text];
    
    NSString * md5Password = [NSString stringToMD5:newPassword];
    
    parameters[NC_USER_PASSWORD] = md5Password;
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",NC_SERVICE_URL,NC_DEBUG_LOGIN];
    
    NSLog(@"urlString:%@ , parameters:%@",postUrl,parameters);
    
    [manager POST:postUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismiss];
        
        //判断nav做何动画
        self.isLogin = YES;
        
        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
        
        
        
        [userDefaults setObject:self.userNameTextfield.text forKey:UD_USERNAME];
        
        
        
        
        
        
        
        //判断是否登录成功
        int idNumber = [[responseObject valueForKey:NC_USER_ID] intValue];
        
        NSString *tokenPass = [responseObject valueForKey:NC_TOKEN_PASS];
        
        int clientType = [[responseObject valueForKey:NC_CLIENT_TYPE] intValue];
        
        if (!(idNumber > 0) || !(tokenPass.length > 0) || !(clientType > 0)) {
            
            [SVProgressHUD showErrorWithStatus:@"Failed"];
            
            [SVProgressHUD dismissWithDelay:1];
            
            return;
            
        }
        
        //登录成功
        [userDefaults setBool:YES forKey:USER_IS_LOGIN];
        
        [userDefaults setObject:self.passwordTextfield.text forKey:UD_PASSWORD];
        
        [self.passwordTextfield setText:@""];
        
        
        
        //跳转
        
        if (self.presentingViewController) {
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }else{
            
            UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"MainView" bundle:[NSBundle mainBundle]];
            
            UINavigationController * navigationController = [storyboard instantiateViewControllerWithIdentifier:@"MainViewNavigation"];
            
            [self presentViewController:navigationController animated:YES completion:nil];
            
        }
        
        UserModel * userModel = [[UserModel alloc]init];
        
        userModel.userID = [responseObject valueForKey:NC_USER_ID];
        
        userModel.clientType = [responseObject valueForKey:NC_CLIENT_TYPE];
        
        userModel.tokenPass = [responseObject valueForKey:NC_TOKEN_PASS];
        
        userModel.userName = [responseObject valueForKey:NC_USER_NAME];
        
        //推送绑定账号
        
        [[FIRMessaging messaging] subscribeToTopic:[NSString stringWithFormat:@"%@%@%@",NC_TOPICS,NC_PUSH,self.userModel.userID]];
        
        NSLog(@"success %@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"Incorrect username or password.Please try again."];
        
        [SVProgressHUD dismissWithDelay:1];
        
        NSLog(@"%@",error);
        
    }];
    
}

#pragma mark 获取GUID
- (NSString *)getUniqueStrByUUID
{
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    
    //get the string representation of the UUID
    
    NSString    *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    
    CFRelease(uuidObj);
    
    return uuidString ;
    
}

#pragma mark 限制textfield输入类型
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    
    return [string isEqualToString:filtered];
    
}


#pragma mark 限制输入长度
- (void)textFieldDidChange:(UITextField *)textField
{
    
    if (textField.text.length > 32) {
        
        textField.text = [textField.text substringToIndex:32];
        
    }
    
    
}

#pragma mark textfield return事件
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    
    if (textField == self.userNameTextfield) {
        
        [self.passwordTextfield becomeFirstResponder];
        
    }
    
    if (textField == self.passwordTextfield) {
        
        [self touchLoginButton:self.loginButton];
        
    }
    
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
